package handler

import (
	"context"
	"fmt"
	"github.com/smartwalle/alipay/v3"
	"github.com/smartwalle/xid"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"project/client/global"
	"project/client/internal/logic"
	"project/client/internal/svc"
	"project/client/internal/types"
	"project/weeksrv/weeksrv"
	"strconv"
)

func AliPayHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var tradeNo = fmt.Sprintf("%d", xid.Next())
		orderSn := r.FormValue("orderSn")
		res, err := svcCtx.WeekSrv.GetOrderByOrderSn(context.Background(), &weeksrv.GetOrderByOrderSnReq{OrderSn: orderSn})
		if err != nil {
			return
		}
		fmt.Println(res.Order, "[[[[")
		total := strconv.Itoa(int(res.Order.TotalPrice))
		var p = alipay.TradePagePay{}
		p.NotifyURL = "http://9c514c4.r16.cpolar.top" + "/alipay/notify"
		p.ReturnURL = "http://9c514c4.r16.cpolar.top" + "/alipay/callback"
		p.Subject = "支付测试:" + tradeNo
		p.OutTradeNo = orderSn
		p.TotalAmount = total
		p.ProductCode = "FAST_INSTANT_TRADE_PAY"
		url, _ := global.Client.TradePagePay(p)
		fmt.Println(url.String(), "////")
		r.Form.Set("url", url.String())

		var req types.AliPayReq
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := logic.NewAliPayLogic(r.Context(), svcCtx)
		resp, err := l.AliPay(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}
